from typing import Dict, Any, Optional, List
from .ai_base import BaseAIService, AIServiceProvider, AIServiceType
from .openai_service import OpenAIService
from .stability_ai_service import StabilityAIService
from .google_veo3_service import GoogleVeo3Service
from .runway_ml_service import RunwayMLService
from .jimeng_ai_service import JimengAIService
from app.core.ai_services_config import ai_services_config

class AIServiceFactory:
    """AI服务工厂类"""
    
    _service_classes = {
        AIServiceProvider.OPENAI_DALLE: OpenAIService,
        AIServiceProvider.STABILITY_AI: StabilityAIService,
        AIServiceProvider.GOOGLE_VEO3: GoogleVeo3Service,
        AIServiceProvider.RUNWAY_ML: RunwayMLService,
        AIServiceProvider.JIMENG_AI: JimengAIService,
        # 可以继续添加其他服务商
    }
    
    @classmethod
    def create_service(cls, provider: AIServiceProvider, config: Optional[Dict[str, Any]] = None) -> BaseAIService:
        """创建AI服务实例"""
        
        # 如果没有提供配置，使用统一配置管理器获取
        if config is None:
            config = ai_services_config.get_service_config(provider)
        
        service_class = cls._service_classes.get(provider)
        
        if not service_class:
            raise ValueError(f"不支持的AI服务提供商: {provider}")
        
        return service_class(config)
    
    @classmethod
    def get_available_providers(cls) -> List[AIServiceProvider]:
        """获取所有可用的服务提供商"""
        return list(cls._service_classes.keys())

class AIServiceManager:
    """AI服务管理器 - 支持多服务商路由和负载均衡"""
    
    def __init__(self):
        self.services: Dict[AIServiceProvider, BaseAIService] = {}
        self.routing_config: Dict[AIServiceType, List[AIServiceProvider]] = {}
        self.default_providers: Dict[AIServiceType, AIServiceProvider] = {}
    
    def register_service(self, provider: AIServiceProvider, config: Optional[Dict[str, Any]] = None):
        """注册AI服务"""
        service = AIServiceFactory.create_service(provider, config)
        self.services[provider] = service
        
        # 自动配置路由
        supported_services = service.get_supported_services()
        for service_type in supported_services:
            if service_type not in self.routing_config:
                self.routing_config[service_type] = []
            self.routing_config[service_type].append(provider)
            
            # 设置默认提供商（第一个注册的）
            if service_type not in self.default_providers:
                self.default_providers[service_type] = provider
    
    def get_service(self, provider: AIServiceProvider) -> Optional[BaseAIService]:
        """获取指定的AI服务"""
        return self.services.get(provider)
    
    def get_best_service_for_type(self, service_type: AIServiceType, preferred_provider: Optional[AIServiceProvider] = None) -> Optional[BaseAIService]:
        """为指定服务类型获取最佳的AI服务"""
        
        # 如果指定了首选提供商，优先使用
        if preferred_provider and preferred_provider in self.services:
            service = self.services[preferred_provider]
            if service_type in service.get_supported_services():
                return service
        
        # 使用默认提供商
        default_provider = self.default_providers.get(service_type)
        if default_provider and default_provider in self.services:
            return self.services[default_provider]
        
        # 使用第一个可用的服务
        available_providers = self.routing_config.get(service_type, [])
        for provider in available_providers:
            if provider in self.services:
                return self.services[provider]
        
        return None
    
    def get_all_services_for_type(self, service_type: AIServiceType) -> List[BaseAIService]:
        """获取支持指定服务类型的所有AI服务"""
        services = []
        available_providers = self.routing_config.get(service_type, [])
        for provider in available_providers:
            if provider in self.services:
                services.append(self.services[provider])
        return services
    
    def get_services_by_type(self, service_type: AIServiceType) -> Dict[AIServiceProvider, BaseAIService]:
        """获取支持指定服务类型的所有AI服务（返回字典格式）"""
        services = {}
        available_providers = self.routing_config.get(service_type, [])
        for provider in available_providers:
            if provider in self.services:
                services[provider] = self.services[provider]
        return services
    
    def get_all_services(self) -> Dict[AIServiceProvider, BaseAIService]:
        """获取所有已注册的AI服务"""
        return self.services.copy()
    
    def get_service_status(self) -> Dict[str, Any]:
        """获取所有服务状态"""
        status = {}
        
        # 获取配置管理器中的服务状态
        config_status = ai_services_config.get_service_status()
        
        for provider, service in self.services.items():
            provider_status = config_status.get(provider.value, {})
            status[provider.value] = {
                "provider": provider.value,
                "supported_services": [s.value for s in service.get_supported_services()],
                "available": True,  # TODO: 实现健康检查
                "config_valid": provider_status.get("config_valid", False),
                "enabled": provider_status.get("enabled", True),
                "api_key_configured": provider_status.get("api_key_configured", False)
            }
        
        return status
    
    def register_all_enabled_services(self):
        """注册所有已启用的AI服务"""
        enabled_services = ai_services_config.get_enabled_services()
        
        for provider, config in enabled_services.items():
            try:
                self.register_service(provider, config)
                print(f"✓ 已注册AI服务: {provider.value}")
            except Exception as e:
                print(f"✗ 注册AI服务失败 {provider.value}: {str(e)}")
    
    def get_service_config_status(self) -> Dict[str, Any]:
        """获取服务配置状态概览"""
        return ai_services_config.get_service_status()

# 全局AI服务管理器实例
ai_service_manager = AIServiceManager()